package sis.ui;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-08-05 18:31
 * @notify
 * @version 1.0
 */

import sun.plugin.dom.core.Document;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

//文本超长过滤器
public class LimitFilter extends DocumentFilter {
    private int limit;

    public LimitFilter(int limit) {
        this.limit = limit;
    }

    public void insertString(
            DocumentFilter.FilterBypass bypass,
            int offset,
            String str,
            AttributeSet attrSet) throws BadLocationException {
        replace(bypass, offset, 0, str, attrSet);
    }

    public void replace(DocumentFilter.FilterBypass bypass,
                        int offset,
                        int length,
                        String str,
                        AttributeSet attrSet) throws BadLocationException {
        int newLength =
                bypass.getDocument().getLength() - length + str.length();
        if (newLength > limit) {
            throw new BadLocationException("超长", offset);
        }
        bypass.replace(offset, length, str, attrSet);
    }
}
